﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
namespace Restful_Api.Helpers
{
    /// <summary>
    /// 动态的属性 单个资源的数据塑性
    /// </summary>
    public static class ObjectExtensions
    {
        public static ExpandoObject ShapeData<TSouce>(this TSouce source, string fields)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
            var expandoObject= new ExpandoObject();
            if (string.IsNullOrWhiteSpace(fields))
            {
                var propertyInfos = typeof(TSouce)
                    .GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                foreach (var item in propertyInfos)
                {
                    var propertyValue = item.GetValue(source);
                    ((IDictionary<string, object>)expandoObject).Add(item.Name, propertyValue);
                }
                    
            }
            else
            {
                var fieldsAfterSplit = fields.Split(',');
                foreach (var item in fieldsAfterSplit)
                {
                    var propertyName = item.Trim();
                    var properInfo = typeof(TSouce)
                    .GetProperty(propertyName,BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                    if (properInfo == null)                    
                        throw new Exception($"在 {typeof(TSouce)}上没有找到{propertyName}");
                    
                    var propertyValue = properInfo.GetValue(source);
                    ((IDictionary<string, object>)expandoObject).Add(properInfo.Name, propertyValue);
                }
            }
            return expandoObject;
        }
    }
}
